/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-08-25 11:18:12
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-08-25 12:01:43
 * @FilePath: /0825/sharemem/processA.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-08-25 09:13:23
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-08-25 11:11:23
 * @FilePath: /0825/sharemem/processA.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include"comm.hpp"

extern log llog;

int main()
{
    Init init;  // 创建管道

    sleep(3);
    int shmid = CreateShm();
    llog(Debug, "processA create shm done");

    sleep(3);
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);    // 将共享内存 与 进程A 挂接
    llog(Debug, "attach shm done, shmaddr: 0x%x", shmaddr);


    // 打开信道
    int fd = open(FIFO_FILE, O_RDONLY); // 等待 写入方打开 管道文件之后，自己才会向后执行，open 阻塞了！
    if(fd < 0)
    {
        // perror("open");
        // logmessage(Fatal, "error string: %s, error code: %d\n", strerror(errno), errno);

        // logg.logmessage(Fatal, "error string: %s, error code: %d\n", strerror(errno), errno);
        llog(Fatal, "error string: %s, error code: %d\n", strerror(errno), errno);
        exit(FIFO_OPEN_ERR);
    }

    
    // ipc code
    struct shmid_ds shmds;
    while(true)
    {
        // 被通知要 开始 读了，那么才继续执行，然后开始 从共享内存中 读取
        char c;
        ssize_t s = read(fd, &c, 1);    // 对方如果 没有向 这个管道里 写，你 read 就 阻塞
        if(s == 0)  break;
        else if(s < 0)  break;


        cout << "client say@ " << shmaddr << endl;  // 直接使用 共享内存
        sleep(1);

        shmctl(shmid, IPC_STAT, &shmds);
        cout << "shm size: " << shmds.shm_segsz << endl;
        cout << "shm nattch: " << shmds.shm_nattch << endl;
        // cout << "shm __key: " << shmds.shm_perm.__key << endl;
        printf("shm __key: 0x%x\n", shmds.shm_perm.__key);
        cout << "shm mode: " << shmds.shm_perm.mode << endl;
        
    }






    sleep(3);
    shmdt(shmaddr); // 手动 去关联
    llog(Debug, "detach shm done, shmaddr: 0x%x", shmaddr);

    sleep(3);
    shmctl(shmid, IPC_RMID, nullptr);   // 手动释放共享内存
    llog(Debug, "destroy shm done, shmaddr: 0x%x", shmaddr);


    // llog(Debug, "processA quit...");
    close(fd);  // 关闭管道文件
    return 0;
}